/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.oauth.config

import com.gitee.minimalismstyle.fresh.oauth.provider.AnyAuthenticationProvider
import com.gitee.minimalismstyle.fresh.oauth.service.FreshUserDetailsService
import com.gitee.minimalismstyle.fresh.sys.api.service.SysSmscodeService
import com.gitee.minimalismstyle.fresh.sys.api.service.SysUserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.core.annotation.Order
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter

@Primary
@Configuration
@Order(90)
class AuthSecurityConfig : WebSecurityConfigurerAdapter() {

    @Autowired
    val userDetailsService: FreshUserDetailsService? = null
    @Autowired
    val smscodeService: SysSmscodeService? = null
    @Autowired
    val userService: SysUserService? = null

    override fun configure(http: HttpSecurity) {

        http
                .authorizeRequests()
                .antMatchers("/actuator/**").permitAll()
                .anyRequest().authenticated()
                .and().csrf().disable().cors().disable()

    }

    override fun configure(auth: AuthenticationManagerBuilder) {
        auth.authenticationProvider(anyAuthenticationProvider())
    }

    @Bean
    fun anyAuthenticationProvider(): AnyAuthenticationProvider {
        val provider = AnyAuthenticationProvider()
        // 设置userDetailsService
        provider.userDetailsService = userDetailsService
        provider.smscodeService = smscodeService
        provider.userService = userService
        return provider
    }

    @Bean
    override fun authenticationManagerBean(): AuthenticationManager {
        return super.authenticationManagerBean()
    }

}
